package Servlet;

import dao.UserDao;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String username = req.getParameter("username");

    String password = req.getParameter("password");

    User user = userDao.getUser(username,password);
// 设置服务器响应内容类型和字符编码
       resp.setHeader("content-type","text/html;charset=utf-8");
       if(user!=null&&user.getUsername()!=null){
           // 登陆成功， 转到初始页面
           HttpSession session = req.getSession();
           session.setAttribute("username",user.getUsername());
           req.removeAttribute("error");
           req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
       }else{
           req.setAttribute("error","您的账号或密码有误，请重新登录");
           req.getRequestDispatcher("/index.jsp").forward(req, resp);
       }

}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        this.doGet(req,resp);
    }

}
